<template>
  <div class="chat">
    <ChatHeader :chat-params="chatParams" />
    <ChatContent 
      :has-next-page="hasNextPage" 
      :msg-list="msgList"
      @queryChatRecord="queryChatRecord"
      ref="ChatContent"
      :loading-list-data="loadingListData"
    />
    <ChatFooter ref="chatFooterRef" />
  </div>
</template>

<script>
/** vue */
import ChatHeader from './components/ChatHeader';
import ChatContent from './components/ChatContent';
import ChatFooter from './components/ChatFooter';
import * as IMApi from '@src/api/ImApi.js';

export default {
  name: 'chat',
  provide() {
    return {
      addMsg: this.addMsg,
      delMsg:this.delMsg,
      chatParams:()=>this.chatParams
    };
  },
  data() {
    return {
      msgList: [],
      chatParams: {}, // 当前会话信息
      hasNextPage:false,
      total:10, // 请求数量
      loadingListData:true,
    };
  },
  created() {
    this.$eventBus.$on('initPage_insideIM', this.initPage);
    this.$eventBus.$on('addMsg_insideIM', this.addMsg);
    this.$eventBus.$on('clear_chat_msg', this.handleClearMsg);
    this.$eventBus.$on('websocket_insideIm_chat', res => {
      if (
        [
          'chatNewMessage',
          'chatGroupNewMessage',
          'chatNewGroup',
          'groupDynamic',
        ].includes(res.notifyType)
      ) {
        if (res.content.chatUuid == this.chatParams.chatUuid) {
          this.addMsg(res.content);
          const msg = res.content;
          msg.recentMessage = msg.acceptRecentMessage;
          this.$eventBus.$emit('updateCurrentChat', msg)
        }
      }
    });
  },
  destroyed(){
    this.$eventBus.$off('initPage_insideIM')
    this.$eventBus.$off('addMsg_insideIM')
    this.$eventBus.$off('websocket_insideIm_chat')
    this.$eventBus.$off('clear_chat_msg')
  },
  methods: {
    // 清空聊天框内容
    handleClearMsg() {
      this.$refs.chatFooterRef.message = '';
    },
    /** 添加消息 */
    addMsg(msg) {
      this.msgList.push(msg);
      this.$eventBus.$emit('scrollBottom_insideIM');
    },
    /** 删除消息 */
    delMsg(idx){
      this.msgList.splice(idx, 1)
    },
    /** 查询聊天记录 */
    async queryChatRecord(more = false) {
      const params = {
        chatUuid: this.chatParams.chatUuid,
        pageNum:1,
        pageSize: more
          ? this.msgList.length + 10 > this.total
            ? this.total
            : this.msgList.length + 10
          : 10,
        chatType: this.chatParams.chatType,
      };
      try {
        const { code, data, message } = await IMApi.queryChatRecord_inside(
          params
        );
        if (code == 0) {
          this.hasNextPage = data.hasNextPage
          this.total = data.total
          if(more){
            let temp = data.list.filter(v=>!this.msgList.find(v1=>v.id == v1.id))
            this.msgList.unshift(
              ...temp
            );
            this.resetScrollBarHeight(this.$refs.ChatContent.$el)
          }else{
            this.msgList = data.list || [];
          }
        } else {
          this.$message.error(message);
          return Promise.reject(message);
        }
      } catch (err) {
        console.error(err);
        return Promise.reject(this.$t('system.internalCoordination.text3'));
      }
    },
    async initPage(data) {
      try{
        this.loadingListData = true
        this.reset()
        if (!data) return this.$message.error(this.$t('system.internalCoordination.text4'));
        this.chatParams = data
        // 判断是否需要发送报表信息
        if (sessionStorage.getItem('inside_bizInfo')) {
          const { url } = JSON.parse(sessionStorage.getItem('inside_bizInfo'));
          if (url.includes('/stats/intelligenceReport/charts') && !sessionStorage.getItem('chatError')) {
            const params = {};
            const newUrl = new URL(url);
            for (const [key, value] of newUrl.searchParams) {
              params[key] = value;
            }
            params.routingKey = 'menuName=' + params?.menuName + '&chartName=' + params?.routingKey;
            await this.sendReportMessage(params.reportId, params.chartName, params.routingKey);
            sessionStorage.removeItem('inside_bizInfo');
          }
        }
        await this.queryChatRecord();
        this.$eventBus.$emit('scrollBottom_insideIM');
        // 判断是否需要发送业务信息
        if(sessionStorage.getItem('inside_bizInfo')){
          this.sendBizMessage(JSON.parse(sessionStorage.getItem('inside_bizInfo')))
          sessionStorage.removeItem('inside_bizInfo')
        }
      }finally{
        this.loadingListData = false
      }
    },
    reset(){
      this.hasNextPage = false
      this.total = 10
      this.msgList = []
    },
    // 重置滚动条高度
    resetScrollBarHeight(node){
      const previousScrollHeightMinusTop = node.scrollHeight - node.scrollTop;
      this.$nextTick(() => {
        node.scrollTop = node.scrollHeight - previousScrollHeightMinusTop;
      });
    },
    // 前端发送卡片询问消息并渲染
    async sendBizMessage(message){
      const { url, userId } = message
      if(!url) return
      let messageType = ''
      let bizId = ''
      let taskModeIsMyself = false
      // 工单详情
      if(url.includes('/task/view')){
        const index = url.lastIndexOf('/');
        messageType = 'task'
        bizId = url.substring(index + 1, url.length).split('?')[0]
        taskModeIsMyself = userId === window?.parent?.loginUser?.userId && messageType === 'task';
      }
      // 事件详情
      if(url.includes('/event/view')){
        const index = url.lastIndexOf('/');
        messageType = 'event'
        bizId = url.substring(index + 1, url.length).split('?')[0]
      }

      // 客户详情
      if(url.includes('/customer/view')){
        const index = url.lastIndexOf('/');
        messageType = 'customer'
        bizId = url.substring(index + 1, url.length).split('?')[0]
      }
      if(messageType && bizId && !taskModeIsMyself){
        try{
          const params = {
            messageType,
            bizId,
          }
          const {code, data} = await IMApi.queryBizMessageContent(params)
          if(code == 0){
            this.addMsg({
              messageType:`biz_${messageType}`,
              messageContent:{
                ...data,
                pageUrl:url
              }
            })
          }
        }catch(err){
          console.error(err)
        }
      }
    },

    async sendReportMessage(reportId, reportName, routingKey) {
      let reportThumbnail = '';
      let reportThumbnailType = 'sourceRoute';
      await IMApi.getReportMessageContent({id: reportId}).then(res => {
        if (res?.message == '' || !res.success) {
          reportThumbnail = 'https://static-test.shb.ltd/image/pc/zh/report/no_data.png';
          reportThumbnailType = 'sourceRoute';
        } else {
          reportThumbnail = res.message;
          reportThumbnailType = 'url';
        }
      })
      const params = {
        chatType: this.chatParams.chatType,
        chatUuid: this.chatParams.chatUuid,
        messageType: 'report',
        messageContent: {
          reportId,
          reportName,
          reportThumbnailType,
          reportThumbnail,
          routingKey
        }
      }
      await IMApi.sendReportMessage(params).then(res => {
        if (res.success) {
          this.$message.success(this.$t('report.customer.shareSuccess'));
        } else {
          this.$message.error(res.message);
        }
      })
    },
  },
  components: {
    ChatHeader,
    ChatContent,
    ChatFooter,
  },
};
</script>

<style scoped lang="scss">
.fixed {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 99;
}
.chat {
  width: 100%;
  max-width: 592px;
  height: 100%;
  background-color: #ffffff;
  box-shadow: -6px 0px 16px 0px rgba(0, 0, 0, 0.1);
  filter: blur(0px);
  display: flex;
  flex-direction: column;
}
</style>
